#include "YGPlatform.h"

#if (YG_OS_TYPE == YG_OS_TYPE_ANDROID)

#include "YGRenderMethodManagerAndroid.h"

#include "YGError.h"

namespace YoghurtGum
{

	RenderMethodManagerAndroid::RenderMethodManagerAndroid()
	{

	}

	RenderMethodManagerAndroid::~RenderMethodManagerAndroid()
	{

	}

	typedef RenderMethod* (*DLL_START_PLUGIN)(Device*);

	bool RenderMethodManagerAndroid::Destroy()
	{
		delete m_Loaded;
	}

	void RenderMethodManagerAndroid::InstallRenderer(const char* a_PluginName)
	{
		const char* error;

		char path[] = "libRenderMethodOpenGLES.so";

		Log::GetSingleton().Print("RenderMethodManagerAndroid::InstallRenderer - Path to library: %s", path);

		void* handle = dlopen(path, RTLD_LAZY);
		if (!handle)
		{
			Log::GetSingleton().Print("RenderMethodManagerAndroid::InstallRenderer - Could not get handle to RenderMethod.");
			return;
		}

		// reset error
		dlerror();

		DLL_START_PLUGIN func_start = (DLL_START_PLUGIN)dlsym(handle, "Install");
		if ((error = dlerror()))
		{
			Log::GetSingleton().Print("RenderMethodManagerAndroid::InstallRenderer - Could not get handle to RenderMethod's Install function. (%s)", error);
			return;
		}

		Log::GetSingleton() << "Installed RenderMethod!" << ENDL; 

		RenderMethod* loaded = func_start(&Device::Get());
		AddRenderer(loaded, loaded->GetName());
	}

	void RenderMethodManagerAndroid::AddRenderer(RenderMethod* a_RenderMethod, const char* a_Name)
	{
		YG_STUB;
		m_Loaded = a_RenderMethod;
	}

	RenderMethod* RenderMethodManagerAndroid::GetCurrent()
	{
		YG_STUB;
		return m_Loaded;
	}

	RenderMethod* RenderMethodManagerAndroid::GetRenderMethod(const char* a_Name)
	{
		YG_STUB;
		return m_Loaded;
	}

	bool RenderMethodManagerAndroid::SetProperty(const char* a_Name, void* a_Data)
	{
		if (!strcmp(a_Name, "WindowHandle"))
		{
			m_Window = a_Data;
		}
		return false;
	}

	RenderMethod* RenderMethodManagerAndroid::ChooseRenderMethod(Window* a_Window)
	{
		InstallRenderer("Awesome");
		m_Loaded->SetProperty("WindowHandle", m_Window);
		//m_Loaded->SetDeviceDimensions(Device::Get().GetWidth(), Device::Get().GetHeight());
		bool init = m_Loaded->Init();
		return m_Loaded;
	}

}

#endif